from flask import Blueprint, request
from flask_jwt_extended import jwt_required

from model.score_model import ScoreModel
from service.score_service import ScoreService

# 声明蓝图
score_router = Blueprint(name="score", import_name=__name__)
score_service = ScoreService()


@score_router.route("/score/get")
@jwt_required()
def score_get():
    """
    查找
    {id: 1}
    :return:
    """
    # 获取请求参数
    data = request.args
    case_id = data.get("id")
    # 如果有id则进行数据查找
    if case_id:
        score = score_service.get(int(case_id))
        # 如果查询到结果
        if score:
            datas = [score.as_dict()]
            return {"code": 0, "msg": "获取数据成功", "data": datas}
        else:
            # 如果没有数据，则返回数据已存在
            return {"code": 40004, "msg": "数据已存在"}
    else:
        # 如果没有id,则返回全部数据
        datas = [score.as_dict() for score in score_service.list()]
        return {"code": 0, "msg": "获取数据成功", "data": datas}


@score_router.route("/score/post", methods=["POST"])
@jwt_required()
def score_post():
    """
    新增
    :return:
    """
    # 获取请求体
    data = request.json
    # 构造对象
    score = ScoreModel(**data)
    # 新增
    id = score_service.create(score)
    if id:
        # 存在id, 则证明新增成功了
        return {"code": 0, "msg": "添加数据成功", "data": {"score_id": id}}
    else:
        return {"code": 40001, "msg": "数据已存在"}


@score_router.route("/score/put", methods=["POST"])
@jwt_required()
def score_put():
    """
    修改
    :return:
    """
    # 获取请求体
    data = request.json
    # 构造对象
    score = ScoreModel(**data)
    # 修改
    id = score_service.update(score)
    if id:
        # 存在id, 则证明新增成功了
        return {"code": 0, "msg": "修改数据成功", "data": {"score_id": id}}
    else:
        return {"code": 40001, "msg": "修改数据失败"}


@score_router.route("/score/delete", methods=["POST"])
@jwt_required()
def score_delete():
    """
    测试用例的删除
    {"id": 1}
    :return:
    """
    # 获取请求体
    data = request.json
    delete_id = data.get("id")
    if delete_id:
        id = score_service.delete(delete_id)
        if id:
            # 存在测试用例id,则证明用例修改成功了
            return {"code": 0, "msg": f"删除数据成功", "data": {"score_id": id}}
        else:
            return {"code": 40001, "msg": "删除数据失败"}
